<?php
namespace app\common\service;

use think\facade\Db;
use app\common\model\MembershipPlan;
use app\common\model\UserMembership;

/**
 * 会员权限检查服务
 */
class MembershipService
{
    /**
     * 获取用户的会员信息
     */
    public static function getUserMembership($userId)
    {
        if (!$userId) {
            return null;
        }

        return Db::name('gf_user_memberships')
            ->where('user_id', $userId)
            ->where('status', 'active')
            ->where('end_date', '>=', date('Y-m-d'))
            ->order('end_date', 'desc')
            ->find();
    }

    /**
     * 获取会员套餐信息
     */
    public static function getMembershipPlan($planType)
    {
        return Db::name('gf_membership_plans')
            ->where('plan_type', $planType)
            ->where('is_active', 1)
            ->find();
    }

    /**
     * 检查用户是否可以创建应用
     */
    public static function canCreateApp($userId)
    {
        if (!$userId) {
            return ['can_create' => false, 'reason' => '用户未登录'];
        }

        // 获取用户当前会员信息
        $userMembership = self::getUserMembership($userId);
        
        if (!$userMembership) {
            return ['can_create' => false, 'reason' => '您还没有开通会员，请先购买会员'];
        }

        // 获取会员套餐详情
        $plan = self::getMembershipPlan($userMembership['plan_type']);
        if (!$plan) {
            return ['can_create' => false, 'reason' => '会员套餐信息不存在'];
        }

        // 检查会员是否已过期
        if (strtotime($userMembership['end_date']) < time()) {
            return ['can_create' => false, 'reason' => '您的会员已过期，请续费后继续使用'];
        }

        // 检查应用数量限制
        if ($plan['app_limit'] == -1) {
            // -1 表示无限制
            return ['can_create' => true, 'reason' => ''];
        }

        // 获取用户已创建的应用数量
        $appCount = Db::name('gf_apps')
            ->where('user_id', $userId)
            ->where('is_del', 0)
            ->count();

        if ($appCount >= $plan['app_limit']) {
            return [
                'can_create' => false, 
                'reason' => "您的{$plan['name']}会员最多只能创建{$plan['app_limit']}个应用，已达到上限"
            ];
        }

        return ['can_create' => true, 'reason' => ''];
    }

    /**
     * 检查会员是否即将到期（7天内到期）
     */
    public static function checkMembershipExpiry($userId)
    {
        if (!$userId) {
            return ['will_expire' => false, 'days_left' => 0, 'message' => ''];
        }

        $userMembership = self::getUserMembership($userId);
        if (!$userMembership) {
            return ['will_expire' => false, 'days_left' => 0, 'message' => '您还没有开通会员'];
        }

        $endDate = strtotime($userMembership['end_date']);
        $now = time();
        $daysLeft = ceil(($endDate - $now) / 86400); // 86400 = 24 * 60 * 60

        if ($daysLeft <= 7 && $daysLeft > 0) {
            return [
                'will_expire' => true, 
                'days_left' => $daysLeft, 
                'message' => "您的会员将在{$daysLeft}天后到期，请及时续费"
            ];
        } elseif ($daysLeft <= 0) {
            return [
                'will_expire' => true, 
                'days_left' => 0, 
                'message' => '您的会员已到期，请续费后继续使用'
            ];
        }

        return ['will_expire' => false, 'days_left' => $daysLeft, 'message' => ''];
    }

    /**
     * 获取用户的应用创建限制信息
     */
    public static function getAppLimitInfo($userId)
    {
        if (!$userId) {
            return [
                'current_count' => 0,
                'max_limit' => 0,
                'can_create' => false,
                'membership_status' => 'no_login',
                'expiry_info' => ['will_expire' => false, 'days_left' => 0, 'message' => '']
            ];
        }

        // 获取用户当前会员信息
        $userMembership = self::getUserMembership($userId);
        $expiryInfo = self::checkMembershipExpiry($userId);
        
        if (!$userMembership) {
            $currentCount = Db::name('gf_apps')
                ->where('user_id', $userId)
                ->where('is_del', 0)
                ->count();
            
            return [
                'current_count' => $currentCount,
                'max_limit' => 0,
                'can_create' => false,
                'membership_status' => 'no_membership',
                'expiry_info' => $expiryInfo
            ];
        }

        // 获取会员套餐详情
        $plan = self::getMembershipPlan($userMembership['plan_type']);
        if (!$plan) {
            return [
                'current_count' => 0,
                'max_limit' => 0,
                'can_create' => false,
                'membership_status' => 'invalid_plan'
            ];
        }

        // 检查会员是否已过期
        $isExpired = strtotime($userMembership['end_date']) < time();
        $membershipStatus = $isExpired ? 'expired' : $userMembership['status'];

        // 获取用户已创建的应用数量
        $currentCount = Db::name('gf_apps')
            ->where('user_id', $userId)
            ->where('is_del', 0)
            ->count();

        $maxLimit = $plan['app_limit'] == -1 ? 'unlimited' : $plan['app_limit'];
        $canCreate = !$isExpired && ($plan['app_limit'] == -1 || $currentCount < $plan['app_limit']);

        return [
            'current_count' => $currentCount,
            'max_limit' => $maxLimit,
            'can_create' => $canCreate,
            'membership_status' => $membershipStatus,
            'plan_type' => $plan['plan_type'],
            'plan_name' => $plan['name'],
            'membership_end_date' => $userMembership['end_date'],
            'auto_renew' => $userMembership['auto_renew']
        ];
    }

    /**
     * 记录用户操作日志
     */
    public static function logUserAction($userId, $action, $resourceType = null, $resourceId = null, $oldData = null, $newData = null)
    {
        $logData = [
            'user_id' => $userId,
            'action' => $action,
            'resource_type' => $resourceType,
            'resource_id' => $resourceId,
            'old_data' => $oldData ? json_encode($oldData) : null,
            'new_data' => $newData ? json_encode($newData) : null,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
            'created_at' => date('Y-m-d H:i:s')
        ];

        Db::name('gf_user_logs')->insert($logData);
    }

    /**
     * 获取最近的用户活动日志
     */
    public static function getRecentActivities($userId, $limit = 5)
    {
        return Db::name('gf_user_logs')
            ->where('user_id', $userId)
            ->order('created_at', 'desc')
            ->limit($limit)
            ->select()
            ->toArray();
    }
}